<template>
	<view class="mobile-item-container">
		<Navbar :title="noticeId ? '修改公告' : '新增公告'" bgColor="#fff" :h5Show="false"></Navbar>
		<u--form ref="noticeForm" :model="notice" :rules="rules" labelPosition="left">
			<u-form-item label="标题" prop="noticeTitle" borderBottom>
				<u--textarea v-model="notice.noticeTitle" placeholder="请输入标题" :count="false" :maxlength="30"
					:autoHeight="true" confirmType="done"></u--textarea>
			</u-form-item>
			<u-form-item label="姓名" prop="remark" borderBottom>
				<u--textarea v-model="notice.remark" placeholder="发文人名称" :count="false" :maxlength="30"
					:autoHeight="true" confirmType="done"></u--textarea>
			</u-form-item>
			<!--      <u-form-item label="类型" prop="noticeType" borderBottom @click="actionShow = true;">
        <u--input v-model="noticeTypeName" disabled disabledColor="#ffffff" placeholder="请选择类型" border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="状态" prop="status" borderBottom>
        <u-radio-group v-model="notice.status">
          <u-radio shape="circle" label="正常" name="0" checked></u-radio>
          <u-radio shape="circle" label="关闭" name="1"></u-radio>
        </u-radio-group>
      </u-form-item> -->
			<u-form-item label="正文" prop="noticeContent">
				<u--textarea v-model="notice.noticeContent" placeholder="请输入正文" :count="true" :maxlength="600"
					confirmType="done"></u--textarea>
			</u-form-item>
		</u--form>

			<u-upload
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				multiple
				:maxCount="1"
				width="335" 
				height="180"
			></u-upload>
		</u-upload>
		<u-action-sheet :actions="actions" :title="actionTitle" :show="actionShow" @close="actionShow = false"
			@select="actionSelect"></u-action-sheet>
		<u-row :gutter="16" style="margin-top: 36px;">
			<u-col :span="6">
				<u-button v-if="noticeId" type="error" text="删除" @click="del"></u-button>
				<u-button v-else icon="arrow-left" text="返回" plain @click="goBack()"></u-button>
			</u-col>
			<u-col :span="6">
				<u-button type="primary" text="提交" @click="submit"></u-button>
			</u-col>
		</u-row>

	</view>
</template>

<script>
	import * as NoticeApi from '@/api/work/notice'
	import Navbar from '@/components/navbar/Navbar'
    import { ACCESS_TOKEN } from '@/store/mutation-types'
    import storage from '@/utils/storage';
	export default {
		components: {
			Navbar,
		},
		data() {
			return {
				noticeId: undefined,
				notice: {
					noticeTitle: '',
					status: '0',
					noticeContent: '',
					remark: '',
					img: ''
				},
				actionShow: false,
				actions: [{
					name: '通知',
					value: '1'
				}, {
					name: '公告',
					value: '2'
				}],
				actionTitle: '',
				noticeTypeName: null,
				rules: {
					noticeTitle: [{
						required: true,
						message: '请输入帖子标题',
						trigger: ['blur', 'change']
					}],
					noticeType: [{
						required: true,
						message: '请选择帖子类型',
						trigger: ['blur', 'change']
					}],
					status: [{
						required: true,
						message: '请选择帖子状态',
						trigger: ['blur', 'change']
					}],
					noticeContent: [{
						required: true,
						message: '请输入帖子正文',
						trigger: ['blur', 'change']
					}],
				},
			fileList1: []
            }
		},
		onLoad(params) {
			this.noticeId = params.id
			this.loadData()
		},
		methods: {
			loadData() {
				if (this.noticeId) {
					const app = this
					NoticeApi.noticeById(this.noticeId).then(res => {
						app.notice = res.data
					})
				}
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					
					let a = uni.uploadFile({
						url: 'http://localhost:8080/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						// header:{
						// 	"Authorization" : 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjZmNmQ2ZjI2LWMyMjItNGM3NC1iMzY2LWI3MjliNjFmMDgxMSJ9.fVTMb4aeS_fI1OU2aN7AVBrkazvHTSmhpfx6Fy4iMVonWbrixkZvOXLA10zRq2FrFxjG0oIvkR0V4b548MRt7A' 
						// },
						header:{
						"Authorization" : 'Bearer ' + storage.get(ACCESS_TOKEN)	
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								let data = JSON.parse(res.data)
								this.notice.img=data.url
								console.log(this.notice)
								resolve(res.data.url)
							
							}, 1000)
						}
					});
				})
			},
			del() {
				NoticeApi.noticeDelete(this.noticeId).then(res => {
					uni.showToast({
						title: '保存成功！'
					})
				})
			},
			submit() {
				this.$refs.noticeForm.validate().then(res => {
					if (this.noticeId) {
						NoticeApi.noticeModify(this.notice).then(res => {
							uni.showToast({
								title: '提交成功！'
							})
						})
					} else {
						NoticeApi.noticeAdd(this.notice).then(res => {
							uni.showToast({
								title: '提交成功！'
							})
						})
					}
				});
				uni.navigateTo({
					url: '/pages/work/notice/manage'
				})
			},
			actionSelect(item) {
				this.noticeTypeName = item.name;
				this.notice.noticeType = item.value;
				this.$refs.noticeForm.validateField('noticeType');
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>
